#!/bin/bash
#
# KernelSU 安装和配置脚本
# 用于自动化设置 SukiSU-Ultra
#

# 严格模式设置
set -euo pipefail
IFS=$'\n\t'

# 检查必要的工具
command -v curl >/dev/null 2>&1 || { echo "错误: 需要安装 curl" >&2; exit 1; }
command -v git >/dev/null 2>&1 || { echo "错误: 需要安装 git" >&2; exit 1; }
command -v awk >/dev/null 2>&1 || { echo "错误: 需要安装 awk" >&2; exit 1; }

echo ">>> 开始设置 KernelSU..."

echo ">>> 下载并安装 SukiSU-Ultra..."
curl -LSs "https://raw.githubusercontent.com/SukiSU-Ultra/SukiSU-Ultra/main/kernel/setup.sh" | bash -s susfs-main

if [ ! -d "./KernelSU" ]; then
    echo "错误: KernelSU 目录创建失败" >&2
    exit 1
fi

cd ./KernelSU

echo ">>> 获取 KSU API 版本..."
KSU_API_VERSION=$(curl -fsSL "https://raw.githubusercontent.com/SukiSU-Ultra/SukiSU-Ultra/susfs-main/kernel/Makefile" | \
  grep -m1 "KSU_VERSION_API :=" | awk -F'= ' '{print $2}' | tr -d '[:space:]')

if [[ -z "$KSU_API_VERSION" || "$(printf '%s\n' "$KSU_API_VERSION" "3.1.7" | sort -V | head -n1)" != "3.1.7" ]]; then
  echo ">>> 使用默认 API 版本 3.1.7"
  KSU_API_VERSION="3.1.7"
fi

echo ">>> 使用 KSU API 版本: $KSU_API_VERSION"

GIT_HASH=$(git rev-parse --short HEAD)
echo ">>> GIT_HASH: $GIT_HASH"

echo ">>> 修改 Makefile 配置..."

# 备份原始 Makefile
cp kernel/Makefile kernel/Makefile.backup

# 清理旧的版本定义
sed -i '/define get_ksu_version_full/,/endef/d' kernel/Makefile
sed -i '/KSU_VERSION_API :=/d' kernel/Makefile
sed -i '/KSU_VERSION_FULL :=/d' kernel/Makefile

# 创建新的版本定义
VERSION_DEFINITIONS=$(cat <<EOF
  define get_ksu_version_full
  v$KSU_API_VERSION-$GIT_HASH@Suxiaoqing
  endef

  KSU_VERSION_API := $KSU_API_VERSION
  KSU_VERSION_FULL := v$KSU_API_VERSION-$GIT_HASH@Suxiaoqing
EOF
)

# 插入版本定义到 Makefile
awk -v def="$VERSION_DEFINITIONS" '
  /REPO_OWNER :=/ {print; print def; inserted=1; next}
  1
  END {if (!inserted) print def}
' kernel/Makefile > kernel/Makefile.tmp

if [ -f "kernel/Makefile.tmp" ]; then
    mv kernel/Makefile.tmp kernel/Makefile
    echo ">>> Makefile 修改成功"
else
    echo "错误: Makefile 修改失败" >&2
    exit 1
fi

# 计算 KSU 版本号
KSU_VERSION=$(expr $(git rev-list --count main 2>/dev/null || echo 13000) + 10700)
echo ">>> KSU 版本号: $KSU_VERSION"

echo ">>> 验证 Makefile 配置..."
if grep -q "KSU_VERSION_FULL" kernel/Makefile; then
    echo ">>> 版本信息预览:"
    grep -A10 "REPO_OWNER" kernel/Makefile || true
    grep "KSU_VERSION_FULL" kernel/Makefile || true
    echo ">>> SukiSU 补丁应用成功完成！"
else
    echo "警告: 版本信息可能未正确设置" >&2
fi

echo ">>> KernelSU 设置完成！"